﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using cde.UserControl;
using Cit.CDE.Net.Module;
using Cit.CDE.Net.Service.ModuleFactory;
using Cit.CDE.Net.Module.Commons;
using Cit.CDE.Net.Service;
using cde.SystemCommon;
using System.Collections.Generic;
using System.Text;
using Module;

/// <summary>
/// Copyright (C)   jinggubang
/// FileName:        RoleEdit.aspx.cs         
/// Author :         fengs
/// CDT:             2011-12-14           
/// Version:         1.0.0.0                
/// Depiction:       权限管理    
/// </summary>
public partial class main_admin_RoleEdit : UserControl.MenuPathPage
{
    #region 常量
    /// <summary>
    /// FROM标识
    /// </summary>
    private const string FROMFLG = "fromFlg";
    /// <summary>
    /// 角色ID
    /// </summary>
    private const string CHKID = "chkID";
    /// <summary>
    /// 角色Entity名
    /// </summary>
    private const string ROLE_EM_FULL_NAME = "WEB.ROLE_ADD";
    /// <summary>
    /// 角色SESSION
    /// </summary>
    private const string SESSION_ENTITY = "M_ROLE.Entity";
    #endregion

    #region 变量
    /// <summary>
    /// 角色EM
    /// </summary>
    private CDEEntityManager em;
    /// <summary>
    /// FROM标记
    /// </summary>
    private string fromFlg;
    /// <summary>
    /// 主健
    /// </summary>
    private string chkID;

    #endregion

    /// <summary>
    /// 页面初始化
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        this.fromFlg = Obj2String(Request.QueryString[FROMFLG]);
        this.chkID = Obj2String(Request.QueryString[CHKID]);

        //取得角色EM
        em = CDEEMFactory.getEMByFullName(ROLE_EM_FULL_NAME);
        if (!Page.IsPostBack)
        {
            //主健不为空，查出角色修改
            if (chkID == "")
            {
                Session.Add(SESSION_ENTITY, null);
                this.page_title.InnerText = "角色新增";
            }
            else
            {
                // 编辑
                CDESearchCriteria sc;
                List<CDEEntity> listEntity;

                sc = new CDESearchCriteria(this.em);
                sc.PageSize = 0;
                sc.addCondition("ID", this.chkID, CDEConstCompare.Equality);
                listEntity = CDEService.LoadEntities(this.em, sc);

                if (listEntity.Count == 0)
                {
                    base.showMessageErrAndOk("该记录已经被删除或不存在");
                    this.cmdCancel_Click(null, null);
                    return;
                }
                else
                {
                    CDEEntity ent = listEntity[0];
                    //系统中默认的角色名称不能进行修改
                    if (Convert.ToInt32(ent.Id) < 2) 
                    {
                        this.txt_ROLE_NAME.ReadOnly = true;
                    }

                    Session.Add(SESSION_ENTITY, ent);
                }

                this.page_title.InnerText = "角色修改";

            }
            //绑定数据
            BindData();
        }
    }


    /// <summary>
    /// 绑定数据
    /// </summary>
    private void BindData()
    {
        CDEEntity entity = Session[SESSION_ENTITY] as CDEEntity;
        if (entity != null)
        {
            if (this.chkID != "")
            {
                this.roleNo.Value = Obj2String(entity.get("ROLE_ID"));
                this.txt_ROLE_NAME.Text = Obj2String(entity.get("ROLE_NAME"));
                this.txt_ROLE_MEMO.Text = Obj2String(entity.get("ROLE_MEMO"));
                this.functions.Value = Obj2String(entity.get("ROLE_FUNC"));
            }
        }
    }




    /// <summary>
    /// 保存
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void queding_Click(object sender, EventArgs e)
    {
        string name = this.txt_ROLE_NAME.Text;
        CDESearchCriteria scSearch = new CDESearchCriteria(em);
        scSearch.addCondition("ROLE_NAME",name);
        scSearch.addCondition("DEL_FLG", "0", CDEConstCompare.Equality);
        List<CDEEntity> listSearch = CDEService.LoadEntities(em, scSearch);

        if (listSearch.Count > 0) 
        {
            //新增
            if (this.chkID == "") 
            {
                showMessageErrAndOk("角色名称重复");
                return;
            }
            //更新
            if (listSearch.Count > 1 || listSearch[0].Id != this.chkID) 
            {
                showMessageErrAndOk("角色名称重复");
                return;
            }
        }
        
        if (Session[CDEConstants.SESSION_LOIN_OPRATOR] == null)
            return;

        Save(false);
    }

    /// <summary>
    /// 保存
    /// </summary>
    /// <param name="isCommit"></param>
    private void Save(bool isCommit)
    {
        //画面取数据
        ReadRole(isCommit);
        //取得当前ROLE
        CDEEntity entityRole = Session[SESSION_ENTITY] as CDEEntity;
        List<CDEEntity> listEn = new List<CDEEntity>();
        listEn.Add(entityRole);

        bool isSaveError = false;
        if (listEn[0].Id == "")
        {
            //更新到DB
            CDEService.UpdateEntitiesTran(this.em, listEn);
            foreach (CDEEntity entity in listEn)
            {
                if (entity.Result.Equals(CDEDataOperationResult.ERROR))
                {
                    isSaveError = true;
                    break;
                }
            }
        }
        else
        {
            //修改
            List<object[]> list = new List<object[]>();
            list.Add(new object[] { em, listEn });
            CDEService.UpdateEntitiesTran(list);

            foreach (CDEEntity entity in listEn)
            {
                if (entity.Result.Equals(CDEDataOperationResult.ERROR))
                {
                    isSaveError = true;
                    break;
                }
            }
        }


        //判断是否修改成功
        if (isSaveError)
        {
            showMessageErrAndOk(Resources.ResourceErrMsg.SAVE_ERR);
        }
        else
        {
            //操作日志记录
            //Facade.SysLog.AddSysLog(entityRole, this.GetLoginOprator());

            //修改或新增成功提示
            //if (this.fromFlg == "")
            if (false)
            {
                StringBuilder sbr = new StringBuilder();
                sbr.AppendFormat("<script language=\"javascript\">{0}", Environment.NewLine);
                sbr.AppendFormat("alert(\"");
                sbr.AppendFormat(Resources.Resource.RESULT_OK);
                sbr.AppendFormat("\");window.location='RoleEdit.aspx';</script>{0}", Environment.NewLine);
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sbr.ToString());
            }
            else
            {
                StringBuilder sbr = new StringBuilder();
                sbr.AppendFormat("<script language=\"javascript\">{0}", Environment.NewLine);
                sbr.AppendFormat("alert(\"");
                sbr.AppendFormat(Resources.Resource.RESULT_OK);
                sbr.AppendFormat("\");window.location='RoleList.aspx?EM=WEB.ROLE_QUERY&sel_menu_id=" + Sel_MenuNode.Attributes["id"].Value + "&IsBackSc=1';</script>{0}", Environment.NewLine);
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sbr.ToString());
            }


        }
    }


    /// <summary>
    /// 画面取数据
    /// </summary>
    /// <param name="isCommit"></param>
    private void ReadRole(bool isCommit)
    {
        CDEEntity entity = Session[SESSION_ENTITY] as CDEEntity;

        if (entity == null)
            entity = CDEEMServiceFactory.getEMService(em).CreateEntity();

        //新增或修改
        if (entity.Id == "")
        {
            entity.set("ROLE_ID", null);
            entity.Operation = CDEDataOperation.INSERT;
        }
        else
        {
            entity.set("ROLE_ID", this.roleNo.Value);
            entity.Operation = CDEDataOperation.UPDATE;
        }

        foreach (CDEAttribute attribute in this.em.ListAttributes)
        {
            if (attribute.P_type == "T")
                entity.set(attribute.Name, null);
        }
        //角色名称
        entity.set("ROLE_NAME", this.txt_ROLE_NAME.Text);
        //备注
        entity.set("ROLE_MEMO", this.txt_ROLE_MEMO.Text);
        //权限
        entity.set("ROLE_FUNC", this.functions.Value);
        //商户ID
        LoginOprator op = this.GetLoginOprator();
        Session[SESSION_ENTITY] = entity;
    }

    /// <summary>
    /// ojb to string
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    private string Obj2String(object obj)
    {
        return SearchCriteriaWithXml.getObject2String(obj);
    }

    /// <summary>
    /// 返回查询列表
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void cmdCancel_Click(object sender, EventArgs e)
    {
        if (Sel_MenuNode == null)
            return;
        StringBuilder url = new StringBuilder();
        url.Append("RoleList.aspx?EM=");
        url.Append("WEB.ROLE_QUERY");
        url.Append("&sel_menu_id=");
        url.Append(Sel_MenuNode.Attributes["id"].Value);
        url.Append("&IsBackSc=1");
        Response.Redirect(url.ToString());
    }
}
